/*
 * @Author: liuhandong
 * @Date: 2020-9-23 12:55:13
 */
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.XR.ARFoundation;
using System.Collections.Generic;
using System.Collections;

public class UITestAR : MonoBehaviour
{
    public Button btnTest;
    public Button btnTestFace;
    public Button btnClose;
    public GameObject targetPrefab;
    public GameObject sessionPrefab;
    public GameObject originPrefab;
    public GameObject faceOriginPrefab;
    private GameObject mTarget;
    private bool mStarted = false;

    public void Awake()
    {
        btnTest.onClick.AddListener(_OnClickStart);    
        btnTestFace.onClick.AddListener(_OnClickStartFace);  
        btnClose.onClick.AddListener(_OnClickClose);  
    }

    private void _OnClickStart()
    {
        mStarted = true;
        ARManager.Instance.OpenAR(sessionPrefab, originPrefab);
        btnTest.gameObject.SetActive(false);
        btnTestFace.gameObject.SetActive(false);
        btnClose.gameObject.SetActive(true);
    }

    private void _OnClickStartFace()
    {
        mStarted = true;
        ARManager.Instance.OpenAR(sessionPrefab, faceOriginPrefab);
        btnTest.gameObject.SetActive(false);
        btnTestFace.gameObject.SetActive(false);
        btnClose.gameObject.SetActive(true);
    }

    private void _OnClickClose()
    {
        mStarted = false;
        ARManager.Instance.CloseAR();
        btnTest.gameObject.SetActive(true);
        btnTestFace.gameObject.SetActive(true);
        btnClose.gameObject.SetActive(false);
    }

    private List<ARRaycastHit> mHits = new List<ARRaycastHit>();
    private void Update()
    {
        if(mStarted)
        {
            if(Input.touchCount > 0)
            {
                var touch = Input.GetTouch(0);
                if(ARManager.Instance.GetMainScene().GetRaycastMan().Raycast(touch.position, mHits, UnityEngine.XR.ARSubsystems.TrackableType.Planes))
                {
                    _EnsureTarget();
                    mTarget.transform.position = mHits[0].pose.position;
                    mTarget.transform.rotation = mHits[0].pose.rotation;
                }
            }
        }
    }

    private void _EnsureTarget()
    {
        if(mTarget == null)
        {
            mTarget = GameObject.Instantiate(targetPrefab) as GameObject;
        }
    }
}